{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Biome Level statistics for model: WK1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "# import the libraries\n",
    "import ee\n",
    "import pandas as pd\n",
    "import os\n",
    "import numpy as np\n",
    "import random\n",
    "from random import sample\n",
    "import itertools \n",
    "import geopandas as gpd\n",
    "from sklearn.metrics import r2_score\n",
    "from termcolor import colored # this is allocate colour and fonts type for the print title and text\n",
    "from IPython.display import display, HTML"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "#set the working directory of local drive for Grid search result table loading\n",
    "# os.getcwd()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "# initialize the earth engine API\n",
    "ee.Initialize()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 1 Load the required composites and images"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "# load the basic maps that needed for the analysis\n",
    "# load the carbon concentration map\n",
    "carbonConcentration = ee.Image(\"users/leonidmoore/ForestBiomass/Biome_level_Wood_Carbon_Conentration_Map\")\n",
    "# load the root shoot ratio map\n",
    "rootShootRatio = ee.Image(\"users/leonidmoore/ForestBiomass/Root_shoot_ratio_Map\").unmask()\n",
    "# load the two composites tha will be used in the analysis\n",
    "compositeImage = ee.Image(\"users/leonidmoore/ForestBiomass/20200915_Forest_Biomass_Predictors_Image\")\n",
    "compositeImageNew = ee.Image(\"projects/crowtherlab/Composite/CrowtherLab_Composite_30ArcSec\")\n",
    "# load the biome layer \n",
    "biomeLayer = compositeImage.select(\"WWF_Biome\")\n",
    "# define a pixel area layer with unit km2\n",
    "pixelAreaMap = ee.Image.pixelArea().divide(10000);\n",
    "# define the boundary geography reference\n",
    "unboundedGeo = ee.Geometry.Polygon([-180, 88, 0, 88, 180, 88, 180, -88, 0, -88, -180, -88], None, False)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 2 Load the biomass density maps"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "# load the carbon density layers\n",
    "potentialDensity = ee.Image(\"users/nordmannmoore/ForestBiomass/RemoteSensingModel/EnsambleMaps/Predicted_WK1_Potential_density_Ensambled_Mean\").unmask()\n",
    "presentDensity =  ee.Image(\"users/leonidmoore/ForestBiomass/WalkerMap/reprojected_Walker_map_1km\").unmask()\n",
    "\n",
    "# define the standard projection\n",
    "stdProj = potentialDensity.projection();"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 3 Adjust the present and potential density maps"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "# load the present and potential forest cover\n",
    "presentForestCover = compositeImage.select('PresentTreeCover').unmask() # uniform with potential in the  0-1 scale\n",
    "potentialCoverAdjusted = ee.Image(\"users/leonidmoore/ForestBiomass/Bastin_et_al_2019_Potential_Forest_Cover_Adjusted\").unmask().rename('PotentialForestCover')\n",
    "# define the present and potential forest cover masks\n",
    "presentMask= presentForestCover.gt(0)\n",
    "potentialMask= potentialCoverAdjusted.gt(0)\n",
    "\n",
    "# check the difference of the two density maps\n",
    "potentialHigher = potentialDensity.multiply(pixelAreaMap).subtract(presentDensity.multiply(pixelAreaMap)).gte(0)\n",
    "potentialLower = potentialDensity.multiply(pixelAreaMap).subtract(presentDensity.multiply(pixelAreaMap)).lt(0)\n",
    "# replace the lower potential value by present biomass density value\n",
    "agbPotentialDensity = presentDensity.multiply(potentialLower).add(potentialDensity.multiply(potentialHigher))\n",
    "# add the root biomass to the AGB to get TGB\n",
    "tgbPotentialDensity = agbPotentialDensity.multiply(rootShootRatio).add(agbPotentialDensity)\n",
    "tgbPresentDensity = presentDensity.multiply(rootShootRatio).add(presentDensity)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 4 Partioning the potential cover into different landuse types"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Load all the landuse type layers\n",
    "croplandOrg = ee.Image(\"users/leonidmoore/ForestBiomass/HYDE31/cropland_Percent\").rename('cropland').divide(100).reproject(crs=stdProj);\n",
    "grazingOrg = ee.Image(\"users/leonidmoore/ForestBiomass/HYDE31/grazing_Percent\").rename('grazing').divide(100).reproject(crs=stdProj);\n",
    "pastureOrg = ee.Image(\"users/leonidmoore/ForestBiomass/HYDE31/pasture_Percent\").rename('pasture').divide(100).reproject(crs=stdProj);\n",
    "rangelandOrg = ee.Image(\"users/leonidmoore/ForestBiomass/HYDE31/rangeland_Percent\").rename('rangeland').divide(100).reproject(crs=stdProj);\n",
    "urbanOrg = compositeImage.select(['LandCoverClass_Urban_Builtup']).divide(100).unmask().reproject(crs=stdProj);\n",
    "snowIceOrg = compositeImageNew.select(['ConsensusLandCoverClass_Snow_Ice']).divide(100).unmask().reproject(crs=stdProj);\n",
    "openWaterOrg = compositeImageNew.select(['ConsensusLandCoverClass_Open_Water']).divide(100).unmask().reproject(crs=stdProj);\n",
    "# define the total landcover types\n",
    "sumCover = presentForestCover.add(pastureOrg).add(rangelandOrg).add(croplandOrg).add(urbanOrg).add(openWaterOrg).add(snowIceOrg);\n",
    "oneSubtract = ee.Image(1).subtract(sumCover);\n",
    "freeland = oneSubtract.multiply(oneSubtract.gte(0));\n",
    "# get the scale ratio for pixels with sumCover larger than 1\n",
    "scaleRatio = ee.Image(1).subtract(presentForestCover).divide(sumCover.subtract(presentForestCover)).multiply(oneSubtract.lt(0));\n",
    "# get the ratio of these three disturbed maps\n",
    "pasture = pastureOrg.multiply(scaleRatio).multiply(oneSubtract.lt(0)).add(pastureOrg.multiply(oneSubtract.gte(0))).unmask();\n",
    "rangeland = rangelandOrg.multiply(scaleRatio).multiply(oneSubtract.lt(0)).add(rangelandOrg.multiply(oneSubtract.gte(0))).unmask();\n",
    "cropland = croplandOrg.multiply(scaleRatio).multiply(oneSubtract.lt(0)).add(croplandOrg.multiply(oneSubtract.gte(0))).unmask();\n",
    "urban = urbanOrg.multiply(scaleRatio).multiply(oneSubtract.lt(0)).add(urbanOrg.multiply(oneSubtract.gte(0))).unmask();\n",
    "openWater = openWaterOrg.multiply(scaleRatio).multiply(oneSubtract.lt(0)).add(openWaterOrg.multiply(oneSubtract.gte(0))).unmask();\n",
    "snowIce = snowIceOrg.multiply(scaleRatio).multiply(oneSubtract.lt(0)).add(snowIceOrg.multiply(oneSubtract.gte(0))).unmask();\n",
    "sumTT = presentForestCover.add(pasture).add(rangeland).add(cropland).add(urban).add(freeland).add(openWater).add(snowIce).unmask();\n",
    "\n",
    "effectivePotentialMask = freeland.add(rangeland).add(pasture).add(cropland).add(urban).gt(0);\n",
    "# there are some pixels without any landcover survived but with open water and ice and snow. here we mask these pixels out\n",
    "sumlandCover = pastureOrg.add(rangelandOrg).add(croplandOrg).add(urbanOrg).add(freeland);\n",
    "restorationMap = potentialCoverAdjusted.subtract(presentForestCover).mask(effectivePotentialMask).unmask();\n",
    "\n",
    "# sum all these scaled layersv\n",
    "scaledSum = pasture.add(rangeland).add(cropland).add(urban).add(freeland);\n",
    "potentialCoverFinal = restorationMap.add(presentForestCover);\n",
    "# allocate the potential equally to each layer\n",
    "freelandPotentialCover = freeland.divide(scaledSum).multiply(restorationMap).unmask();\n",
    "rangelandPotentialCover = rangeland.divide(scaledSum).multiply(restorationMap).unmask();\n",
    "pasturePotentialCover = pasture.divide(scaledSum).multiply(restorationMap).unmask();\n",
    "croplandPotentialCover = cropland.divide(scaledSum).multiply(restorationMap).unmask();\n",
    "urbanPotentialCover = urban.divide(scaledSum).multiply(restorationMap).unmask();\n",
    "#  allocate the freeland potential in pixels with forest cover larger than 10% to conservation potential\n",
    "freelandForConsevation = freelandPotentialCover.multiply(presentForestCover.gte(0.1)).unmask();\n",
    "maximumPotentialCover = freelandForConsevation.add(presentForestCover);\n",
    "# calucate the reall freeland outside of forest\n",
    "freelandLeftMap = freelandPotentialCover.subtract(freelandForConsevation).unmask()# the left positive pixels are real freeland pixels"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 5 Partioning the biomass potential into different landuse types"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "# calculate the existing carbon, present potential carbon and absolute potential carbon in forests\n",
    "absoluteImage1 = tgbPresentDensity.multiply(pixelAreaMap).multiply(presentMask).divide(1000000000).rename('Present')\n",
    "absoluteImage3 = tgbPotentialDensity.multiply(pixelAreaMap).multiply(potentialCoverFinal.gt(0)).divide(1000000000).rename('AbsolutePotential')\n",
    "# get the sum of the potential covers\n",
    "potentialCoverSum = freelandLeftMap.add(rangelandPotentialCover).add(pasturePotentialCover).add(croplandPotentialCover).add(urbanPotentialCover)\n",
    "\n",
    "trueRestorationPotential = absoluteImage3.subtract(absoluteImage1).multiply(1000000000)\n",
    "ratioPotentialBiomassDensity = absoluteImage1.multiply(potentialCoverFinal.divide(presentForestCover))\n",
    "#  get the real for conservation potential\n",
    "realDensityIncreased = absoluteImage3.subtract(absoluteImage1).mask(absoluteImage3.subtract(ratioPotentialBiomassDensity).gt(0)).unmask()\n",
    "realDensityNotIncreased = absoluteImage3.subtract(absoluteImage1).mask(absoluteImage3.subtract(ratioPotentialBiomassDensity).lte(0)).unmask()\n",
    "trueReforestationPotential = realDensityNotIncreased.add(realDensityIncreased.multiply(ee.Image(1).subtract(presentForestCover.divide(potentialCoverFinal))))\n",
    "\n",
    "conservationPotentialPart1 = realDensityIncreased.multiply(presentForestCover.add(freelandForConsevation).divide(potentialCoverFinal))\n",
    "conservationPotentialPart2 = realDensityNotIncreased.multiply(freelandForConsevation.divide(potentialCoverFinal.subtract(presentForestCover)))\n",
    "\n",
    "# calculate the part of the potential inside the forest cover which was allocate to conservation potential.\n",
    "freelandForConservation1 = realDensityIncreased.multiply(freelandForConsevation.divide(potentialCoverFinal))\n",
    "freelandForConservation = freelandForConservation1.add(conservationPotentialPart2).rename('FreeToConservation')\n",
    "\n",
    "absoluteImage2 = conservationPotentialPart1.add(conservationPotentialPart2).add(absoluteImage1).rename('PresentPotential')\n",
    "\n",
    "trueReforestationPotential = absoluteImage3.subtract(absoluteImage2)\n",
    "\n",
    "absoluteImage4 = trueReforestationPotential.multiply(freelandLeftMap.divide(potentialCoverSum)).rename('FreelandPotential')\n",
    "absoluteImage5 = trueReforestationPotential.multiply(rangelandPotentialCover.divide(potentialCoverSum)).rename('RangelandPotential')\n",
    "absoluteImage6 = trueReforestationPotential.multiply(pasturePotentialCover.divide(potentialCoverSum)).rename('PasturePotential')\n",
    "absoluteImage7 = trueReforestationPotential.multiply(croplandPotentialCover.divide(potentialCoverSum)).rename('CroplandPotential')\n",
    "absoluteImage8 = trueReforestationPotential.multiply(urbanPotentialCover.divide(potentialCoverSum)).rename('UrbanPotential')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Calculate the potential numbers and write into local folder"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\u001b[1m\u001b[34mThe biomass partition results in biome: \n",
      "\u001b[0m\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>Present</th>\n",
       "      <th>PresentPotential</th>\n",
       "      <th>AbsolutePotential</th>\n",
       "      <th>FreelandPotential</th>\n",
       "      <th>RangelandPotential</th>\n",
       "      <th>PasturePotential</th>\n",
       "      <th>CroplandPotential</th>\n",
       "      <th>UrbanPotential</th>\n",
       "      <th>FreeToConservation</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>228.703254</td>\n",
       "      <td>257.437364</td>\n",
       "      <td>281.168861</td>\n",
       "      <td>4.704599</td>\n",
       "      <td>0.075468</td>\n",
       "      <td>8.042988</td>\n",
       "      <td>10.590268</td>\n",
       "      <td>0.318174</td>\n",
       "      <td>6.564083</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>9.864075</td>\n",
       "      <td>12.324969</td>\n",
       "      <td>20.880086</td>\n",
       "      <td>2.126831</td>\n",
       "      <td>0.019516</td>\n",
       "      <td>1.942910</td>\n",
       "      <td>4.411112</td>\n",
       "      <td>0.054748</td>\n",
       "      <td>0.732209</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>3.453565</td>\n",
       "      <td>4.919131</td>\n",
       "      <td>6.143256</td>\n",
       "      <td>0.444280</td>\n",
       "      <td>0.030265</td>\n",
       "      <td>0.437966</td>\n",
       "      <td>0.307579</td>\n",
       "      <td>0.004033</td>\n",
       "      <td>0.500517</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>49.234418</td>\n",
       "      <td>56.830716</td>\n",
       "      <td>75.578369</td>\n",
       "      <td>4.524483</td>\n",
       "      <td>0.024942</td>\n",
       "      <td>5.382451</td>\n",
       "      <td>8.354092</td>\n",
       "      <td>0.461686</td>\n",
       "      <td>2.537341</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>24.401686</td>\n",
       "      <td>26.739961</td>\n",
       "      <td>29.588381</td>\n",
       "      <td>1.313104</td>\n",
       "      <td>0.040701</td>\n",
       "      <td>0.841084</td>\n",
       "      <td>0.601932</td>\n",
       "      <td>0.051599</td>\n",
       "      <td>1.027398</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>5</th>\n",
       "      <td>45.302503</td>\n",
       "      <td>52.268129</td>\n",
       "      <td>55.020322</td>\n",
       "      <td>2.402228</td>\n",
       "      <td>0.000815</td>\n",
       "      <td>0.169989</td>\n",
       "      <td>0.167436</td>\n",
       "      <td>0.011726</td>\n",
       "      <td>3.153295</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>6</th>\n",
       "      <td>57.851302</td>\n",
       "      <td>72.345249</td>\n",
       "      <td>106.928270</td>\n",
       "      <td>7.038770</td>\n",
       "      <td>11.809640</td>\n",
       "      <td>9.061055</td>\n",
       "      <td>6.600767</td>\n",
       "      <td>0.072787</td>\n",
       "      <td>4.637877</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>7</th>\n",
       "      <td>4.801044</td>\n",
       "      <td>6.199524</td>\n",
       "      <td>25.429307</td>\n",
       "      <td>3.527693</td>\n",
       "      <td>6.366182</td>\n",
       "      <td>2.471396</td>\n",
       "      <td>6.761019</td>\n",
       "      <td>0.103493</td>\n",
       "      <td>0.194538</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>8</th>\n",
       "      <td>2.814477</td>\n",
       "      <td>3.266802</td>\n",
       "      <td>4.296112</td>\n",
       "      <td>0.306144</td>\n",
       "      <td>0.336748</td>\n",
       "      <td>0.210285</td>\n",
       "      <td>0.165335</td>\n",
       "      <td>0.010798</td>\n",
       "      <td>0.119475</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>9</th>\n",
       "      <td>4.397676</td>\n",
       "      <td>5.534110</td>\n",
       "      <td>10.466418</td>\n",
       "      <td>1.319835</td>\n",
       "      <td>2.080084</td>\n",
       "      <td>0.748104</td>\n",
       "      <td>0.775178</td>\n",
       "      <td>0.009107</td>\n",
       "      <td>0.213598</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>10</th>\n",
       "      <td>4.478712</td>\n",
       "      <td>6.781524</td>\n",
       "      <td>10.661369</td>\n",
       "      <td>3.870388</td>\n",
       "      <td>0.001748</td>\n",
       "      <td>0.000592</td>\n",
       "      <td>0.006767</td>\n",
       "      <td>0.000350</td>\n",
       "      <td>0.352113</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>11</th>\n",
       "      <td>4.798165</td>\n",
       "      <td>5.751636</td>\n",
       "      <td>11.420600</td>\n",
       "      <td>1.521677</td>\n",
       "      <td>0.020697</td>\n",
       "      <td>1.907961</td>\n",
       "      <td>2.136124</td>\n",
       "      <td>0.082505</td>\n",
       "      <td>0.291840</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>12</th>\n",
       "      <td>2.665324</td>\n",
       "      <td>3.839710</td>\n",
       "      <td>28.196617</td>\n",
       "      <td>11.167824</td>\n",
       "      <td>9.662978</td>\n",
       "      <td>0.944043</td>\n",
       "      <td>2.522133</td>\n",
       "      <td>0.059929</td>\n",
       "      <td>0.314011</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>13</th>\n",
       "      <td>2.159737</td>\n",
       "      <td>2.702164</td>\n",
       "      <td>3.169786</td>\n",
       "      <td>0.169134</td>\n",
       "      <td>0.001260</td>\n",
       "      <td>0.082010</td>\n",
       "      <td>0.201944</td>\n",
       "      <td>0.013275</td>\n",
       "      <td>0.136716</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>sum</th>\n",
       "      <td>444.925937</td>\n",
       "      <td>516.940989</td>\n",
       "      <td>668.947753</td>\n",
       "      <td>44.436990</td>\n",
       "      <td>30.471043</td>\n",
       "      <td>32.242835</td>\n",
       "      <td>43.601688</td>\n",
       "      <td>1.254210</td>\n",
       "      <td>20.775009</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "        Present  PresentPotential  AbsolutePotential  FreelandPotential  \\\n",
       "0    228.703254        257.437364         281.168861           4.704599   \n",
       "1      9.864075         12.324969          20.880086           2.126831   \n",
       "2      3.453565          4.919131           6.143256           0.444280   \n",
       "3     49.234418         56.830716          75.578369           4.524483   \n",
       "4     24.401686         26.739961          29.588381           1.313104   \n",
       "5     45.302503         52.268129          55.020322           2.402228   \n",
       "6     57.851302         72.345249         106.928270           7.038770   \n",
       "7      4.801044          6.199524          25.429307           3.527693   \n",
       "8      2.814477          3.266802           4.296112           0.306144   \n",
       "9      4.397676          5.534110          10.466418           1.319835   \n",
       "10     4.478712          6.781524          10.661369           3.870388   \n",
       "11     4.798165          5.751636          11.420600           1.521677   \n",
       "12     2.665324          3.839710          28.196617          11.167824   \n",
       "13     2.159737          2.702164           3.169786           0.169134   \n",
       "sum  444.925937        516.940989         668.947753          44.436990   \n",
       "\n",
       "     RangelandPotential  PasturePotential  CroplandPotential  UrbanPotential  \\\n",
       "0              0.075468          8.042988          10.590268        0.318174   \n",
       "1              0.019516          1.942910           4.411112        0.054748   \n",
       "2              0.030265          0.437966           0.307579        0.004033   \n",
       "3              0.024942          5.382451           8.354092        0.461686   \n",
       "4              0.040701          0.841084           0.601932        0.051599   \n",
       "5              0.000815          0.169989           0.167436        0.011726   \n",
       "6             11.809640          9.061055           6.600767        0.072787   \n",
       "7              6.366182          2.471396           6.761019        0.103493   \n",
       "8              0.336748          0.210285           0.165335        0.010798   \n",
       "9              2.080084          0.748104           0.775178        0.009107   \n",
       "10             0.001748          0.000592           0.006767        0.000350   \n",
       "11             0.020697          1.907961           2.136124        0.082505   \n",
       "12             9.662978          0.944043           2.522133        0.059929   \n",
       "13             0.001260          0.082010           0.201944        0.013275   \n",
       "sum           30.471043         32.242835          43.601688        1.254210   \n",
       "\n",
       "     FreeToConservation  \n",
       "0              6.564083  \n",
       "1              0.732209  \n",
       "2              0.500517  \n",
       "3              2.537341  \n",
       "4              1.027398  \n",
       "5              3.153295  \n",
       "6              4.637877  \n",
       "7              0.194538  \n",
       "8              0.119475  \n",
       "9              0.213598  \n",
       "10             0.352113  \n",
       "11             0.291840  \n",
       "12             0.314011  \n",
       "13             0.136716  \n",
       "sum           20.775009  "
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# Stack the absolute biomass layers into an Image.\n",
    "absPotentialImage = absoluteImage1.addBands(absoluteImage2).addBands(absoluteImage3).addBands(absoluteImage4).addBands(absoluteImage5).addBands(absoluteImage6).addBands(absoluteImage7).addBands(absoluteImage8).addBands(freelandForConservation)\n",
    "# define the function to do the biome level statistics which could be applied by map      \n",
    "def biomeLevelStat(biome):\n",
    "    biomeMask = biomeLayer.eq(ee.Number(biome))\n",
    "    masked_img = absPotentialImage.mask(biomeMask)\n",
    "    output = masked_img.reduceRegion(reducer= ee.Reducer.sum(),\n",
    "                                     geometry= unboundedGeo,\n",
    "                                     crs='EPSG:4326',\n",
    "                                     crsTransform=[0.008333333333333333,0,-180,0,-0.008333333333333333,90],\n",
    "                                     maxPixels= 1e13)\n",
    "    return output#.getInfo().get('Present')\n",
    "\n",
    "\n",
    "biomeList = ee.List([1,2,3,4,5,6,7,8,9,10,11,12,13,14])\n",
    "statisticTable = biomeList.map(biomeLevelStat).getInfo()\n",
    "# transform into data frame\n",
    "outputTable = pd.DataFrame(statisticTable,columns =['Present','PresentPotential','AbsolutePotential','FreelandPotential','RangelandPotential','PasturePotential','CroplandPotential','UrbanPotential','FreeToConservation'])#.round(1)\n",
    "outputTable.loc['sum'] = outputTable.sum() \n",
    "outputTable.to_csv('Data/BiomeLevelStatistics/StatisticsForModels/WK1_Biome_Level_Statistics.csv',header=True,mode='w+')\n",
    "# display the output of the carbon partitioning\n",
    "print(colored('The biomass partition results in biome: \\n', 'blue', attrs=['bold']))\n",
    "outputTable.head(15)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [],
   "source": [
    "# If you got the error 'EEException: Too many concurrent aggregations.', please re-run this chunck of code again."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\u001b[1m\u001b[34mThe biomass partition results in biome: \n",
      "\u001b[0m\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>Present</th>\n",
       "      <th>PresentPotential</th>\n",
       "      <th>AbsolutePotential</th>\n",
       "      <th>FreelandPotential</th>\n",
       "      <th>RangelandPotential</th>\n",
       "      <th>PasturePotential</th>\n",
       "      <th>CroplandPotential</th>\n",
       "      <th>UrbanPotential</th>\n",
       "      <th>FreeToConservation</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>279.026315</td>\n",
       "      <td>314.085872</td>\n",
       "      <td>343.041564</td>\n",
       "      <td>5.740267</td>\n",
       "      <td>0.092303</td>\n",
       "      <td>9.813583</td>\n",
       "      <td>12.921364</td>\n",
       "      <td>0.388174</td>\n",
       "      <td>8.008917</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>12.034080</td>\n",
       "      <td>15.036380</td>\n",
       "      <td>25.473836</td>\n",
       "      <td>2.594753</td>\n",
       "      <td>0.023949</td>\n",
       "      <td>2.370439</td>\n",
       "      <td>5.381522</td>\n",
       "      <td>0.066793</td>\n",
       "      <td>0.893290</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>4.214778</td>\n",
       "      <td>6.003045</td>\n",
       "      <td>7.496659</td>\n",
       "      <td>0.542121</td>\n",
       "      <td>0.036883</td>\n",
       "      <td>0.534293</td>\n",
       "      <td>0.375394</td>\n",
       "      <td>0.004924</td>\n",
       "      <td>0.610844</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>65.473775</td>\n",
       "      <td>75.575322</td>\n",
       "      <td>100.506556</td>\n",
       "      <td>6.016297</td>\n",
       "      <td>0.033124</td>\n",
       "      <td>7.158023</td>\n",
       "      <td>11.109822</td>\n",
       "      <td>0.613968</td>\n",
       "      <td>3.373905</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>32.450751</td>\n",
       "      <td>35.560268</td>\n",
       "      <td>39.345732</td>\n",
       "      <td>1.745028</td>\n",
       "      <td>0.053713</td>\n",
       "      <td>1.118143</td>\n",
       "      <td>0.799989</td>\n",
       "      <td>0.068590</td>\n",
       "      <td>1.366052</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>5</th>\n",
       "      <td>81.506726</td>\n",
       "      <td>94.040034</td>\n",
       "      <td>98.989825</td>\n",
       "      <td>4.322127</td>\n",
       "      <td>0.001367</td>\n",
       "      <td>0.305315</td>\n",
       "      <td>0.299936</td>\n",
       "      <td>0.021045</td>\n",
       "      <td>5.674159</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>6</th>\n",
       "      <td>70.579286</td>\n",
       "      <td>88.262046</td>\n",
       "      <td>130.454197</td>\n",
       "      <td>8.587408</td>\n",
       "      <td>14.408085</td>\n",
       "      <td>11.054750</td>\n",
       "      <td>8.053106</td>\n",
       "      <td>0.088803</td>\n",
       "      <td>5.658238</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>7</th>\n",
       "      <td>6.385594</td>\n",
       "      <td>8.245581</td>\n",
       "      <td>33.819262</td>\n",
       "      <td>4.691445</td>\n",
       "      <td>8.465855</td>\n",
       "      <td>3.286730</td>\n",
       "      <td>8.992014</td>\n",
       "      <td>0.137637</td>\n",
       "      <td>0.258764</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>8</th>\n",
       "      <td>3.434364</td>\n",
       "      <td>3.986294</td>\n",
       "      <td>5.242266</td>\n",
       "      <td>0.373552</td>\n",
       "      <td>0.410814</td>\n",
       "      <td>0.256609</td>\n",
       "      <td>0.201808</td>\n",
       "      <td>0.013187</td>\n",
       "      <td>0.145774</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>9</th>\n",
       "      <td>5.840211</td>\n",
       "      <td>7.348953</td>\n",
       "      <td>13.904134</td>\n",
       "      <td>1.753783</td>\n",
       "      <td>2.764777</td>\n",
       "      <td>0.994230</td>\n",
       "      <td>1.030285</td>\n",
       "      <td>0.012107</td>\n",
       "      <td>0.283661</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>10</th>\n",
       "      <td>8.057407</td>\n",
       "      <td>12.200280</td>\n",
       "      <td>19.182258</td>\n",
       "      <td>6.964980</td>\n",
       "      <td>0.003135</td>\n",
       "      <td>0.001064</td>\n",
       "      <td>0.012172</td>\n",
       "      <td>0.000628</td>\n",
       "      <td>0.633428</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>11</th>\n",
       "      <td>5.806925</td>\n",
       "      <td>6.961124</td>\n",
       "      <td>13.821681</td>\n",
       "      <td>1.841473</td>\n",
       "      <td>0.025145</td>\n",
       "      <td>2.308991</td>\n",
       "      <td>2.585096</td>\n",
       "      <td>0.099852</td>\n",
       "      <td>0.353268</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>12</th>\n",
       "      <td>3.225829</td>\n",
       "      <td>4.647107</td>\n",
       "      <td>34.122823</td>\n",
       "      <td>13.514570</td>\n",
       "      <td>11.693606</td>\n",
       "      <td>1.142795</td>\n",
       "      <td>3.052221</td>\n",
       "      <td>0.072525</td>\n",
       "      <td>0.380047</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>13</th>\n",
       "      <td>2.634881</td>\n",
       "      <td>3.296638</td>\n",
       "      <td>3.867137</td>\n",
       "      <td>0.206338</td>\n",
       "      <td>0.001536</td>\n",
       "      <td>0.100060</td>\n",
       "      <td>0.246370</td>\n",
       "      <td>0.016195</td>\n",
       "      <td>0.166792</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>sum</th>\n",
       "      <td>580.670921</td>\n",
       "      <td>675.248944</td>\n",
       "      <td>869.267929</td>\n",
       "      <td>58.894141</td>\n",
       "      <td>38.014292</td>\n",
       "      <td>40.445026</td>\n",
       "      <td>55.061099</td>\n",
       "      <td>1.604428</td>\n",
       "      <td>27.807138</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "        Present  PresentPotential  AbsolutePotential  FreelandPotential  \\\n",
       "0    279.026315        314.085872         343.041564           5.740267   \n",
       "1     12.034080         15.036380          25.473836           2.594753   \n",
       "2      4.214778          6.003045           7.496659           0.542121   \n",
       "3     65.473775         75.575322         100.506556           6.016297   \n",
       "4     32.450751         35.560268          39.345732           1.745028   \n",
       "5     81.506726         94.040034          98.989825           4.322127   \n",
       "6     70.579286         88.262046         130.454197           8.587408   \n",
       "7      6.385594          8.245581          33.819262           4.691445   \n",
       "8      3.434364          3.986294           5.242266           0.373552   \n",
       "9      5.840211          7.348953          13.904134           1.753783   \n",
       "10     8.057407         12.200280          19.182258           6.964980   \n",
       "11     5.806925          6.961124          13.821681           1.841473   \n",
       "12     3.225829          4.647107          34.122823          13.514570   \n",
       "13     2.634881          3.296638           3.867137           0.206338   \n",
       "sum  580.670921        675.248944         869.267929          58.894141   \n",
       "\n",
       "     RangelandPotential  PasturePotential  CroplandPotential  UrbanPotential  \\\n",
       "0              0.092303          9.813583          12.921364        0.388174   \n",
       "1              0.023949          2.370439           5.381522        0.066793   \n",
       "2              0.036883          0.534293           0.375394        0.004924   \n",
       "3              0.033124          7.158023          11.109822        0.613968   \n",
       "4              0.053713          1.118143           0.799989        0.068590   \n",
       "5              0.001367          0.305315           0.299936        0.021045   \n",
       "6             14.408085         11.054750           8.053106        0.088803   \n",
       "7              8.465855          3.286730           8.992014        0.137637   \n",
       "8              0.410814          0.256609           0.201808        0.013187   \n",
       "9              2.764777          0.994230           1.030285        0.012107   \n",
       "10             0.003135          0.001064           0.012172        0.000628   \n",
       "11             0.025145          2.308991           2.585096        0.099852   \n",
       "12            11.693606          1.142795           3.052221        0.072525   \n",
       "13             0.001536          0.100060           0.246370        0.016195   \n",
       "sum           38.014292         40.445026          55.061099        1.604428   \n",
       "\n",
       "     FreeToConservation  \n",
       "0              8.008917  \n",
       "1              0.893290  \n",
       "2              0.610844  \n",
       "3              3.373905  \n",
       "4              1.366052  \n",
       "5              5.674159  \n",
       "6              5.658238  \n",
       "7              0.258764  \n",
       "8              0.145774  \n",
       "9              0.283661  \n",
       "10             0.633428  \n",
       "11             0.353268  \n",
       "12             0.380047  \n",
       "13             0.166792  \n",
       "sum           27.807138  "
      ]
     },
     "execution_count": 17,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "deadWoodLitterRatio = ee.Image(\"users/leonidmoore/ForestBiomass/DeadWoodLitter/DeadWood_Litter_Ratio_Map\").unmask()\n",
    "\n",
    "# Stack the absolute biomass layers into an Image.\n",
    "absPotentialImage = absoluteImage1.addBands(absoluteImage2).addBands(absoluteImage3).addBands(absoluteImage4).addBands(absoluteImage5).addBands(absoluteImage6).addBands(absoluteImage7).addBands(absoluteImage8).addBands(freelandForConservation)\n",
    "# define the function to do the biome level statistics which could be applied by map      \n",
    "def biomeLevelStat(biome):\n",
    "    biomeMask = biomeLayer.eq(ee.Number(biome))\n",
    "    masked_img = absPotentialImage.mask(biomeMask).multiply(deadWoodLitterRatio)\n",
    "    output = masked_img.reduceRegion(reducer= ee.Reducer.sum(),\n",
    "                                     geometry= unboundedGeo,\n",
    "                                     crs='EPSG:4326',\n",
    "                                     crsTransform=[0.008333333333333333,0,-180,0,-0.008333333333333333,90],\n",
    "                                     maxPixels= 1e13)\n",
    "    return output#.getInfo().get('Present')\n",
    "\n",
    "\n",
    "biomeList = ee.List([1,2,3,4,5,6,7,8,9,10,11,12,13,14])\n",
    "statisticTable = biomeList.map(biomeLevelStat).getInfo()\n",
    "# transform into data frame\n",
    "outputTable = pd.DataFrame(statisticTable,columns =['Present','PresentPotential','AbsolutePotential','FreelandPotential','RangelandPotential','PasturePotential','CroplandPotential','UrbanPotential','FreeToConservation'])#.round(1)\n",
    "outputTable.loc['sum'] = outputTable.sum()\n",
    "outputTable.to_csv('Data/BiomeLevelStatistics/StatisticsForModels/WK1_Biome_Level_Statistics_with_Litter.csv',header=True,mode='w+')\n",
    "# display the output of the carbon partitioning\n",
    "print(colored('The biomass partition results in biome: \\n', 'blue', attrs=['bold']))\n",
    "outputTable.head(15)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 57,
   "metadata": {},
   "outputs": [],
   "source": [
    "# If you got the error 'EEException: Too many concurrent aggregations.', please re-run this chunck of code again."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
